<template>
    <div class="jxc_reconciliation_form_container">
        <el-form ref="jxcReconciliationForm" :rules="rules" :model="formData" label-width="120px"
                 v-enterToNext>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="对账日期" prop="end_date">
                        <el-date-picker v-model="formData.end_date" type="date"
                                        value-format="yyyy-MM-dd"
                                        :disabled="!isEditFlag" style="width: 100%;" />
                    </el-form-item>
                </el-col>
	            <el-col :span="8" v-if="type === 'sale'">
		            <el-form-item label="客户" prop="client_sid">
			            <vSelectBottom v-model="formData.client_sid" type="clientsDrawer"
			                           @event="handleClientEvent" :options="clientOptions"
			                           :disabled="!isEditFlag" />
		            </el-form-item>
	            </el-col>
	            <el-col :span="8" v-else>
		            <el-form-item label="供应商" prop="supplier_sid">
			            <vSelectBottom v-model="formData.supplier_sid" type="supplierDrawer"
			                           @event="handleSupplierEvent" :options="supplierOptions"
			                           :disabled="!isEditFlag" />
		            </el-form-item>
	            </el-col>
                <el-col :span="8">
                    <el-form-item label="对账编码" prop="code">
                        <el-input v-model="formData.code" autocomplete="off" clearable
                                  :disabled="!isEditFlag"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="type === 'sale' ? '上期末未收款金额' : '上期末未付款金额'" prop="pre_end_amount">
                        <el-input v-model="formData.pre_end_amount" autocomplete="off" clearable
                                  :disabled="disabledPreEndAmount" v-double-input="{len: 4, negative: false}"
                                  @change="calc()"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="本期送货金额" prop="amount">
                        <el-input v-model="formData.amount" autocomplete="off" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="type === 'sale' ? '本期收款金额' : '本期付款金额'" prop="payment_amount">
                        <el-input v-model="formData.payment_amount" autocomplete="off" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="type === 'sale' ? '至本期末未收款金额' : '至本期末未付款金额'" prop="end_amount">
                        <el-input v-model="formData.end_amount" autocomplete="off" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="16">
                    <el-form-item label="备注" prop="note_info">
                        <el-input v-model="formData.note_info" autocomplete="off" clearable
                                  :disabled="!isEditFlag" />
                    </el-form-item>
                </el-col>
                <el-col :span="24" v-if="isEditFlag">
                    <el-form-item label-width="0">
                        <el-button type="success" @click="openSelectDialog()">选单</el-button>
                        <el-button type="danger" @click="clear()" :disabled="dataList.length === 0">清空
                        </el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label-width="0">
                        <vxe-table-template :data="dataList" :options.sync="tableOptions" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script>
import { mapState } from "vuex";
import clothing from "@jxc/utils/clothing";
import SelectOrderAndBill from "./SelectOrderAndBill";

export default {
    name: "ReconciliationForm",
    props: {
        type: {
            type: String,
            default: null,
        },
        row: {
            type: Object,
            default: null,
        },
        detail: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        const _this = this;
        return {
            rules: {
                code: [
                    { required: true, message: "请输入对账编码", trigger: "blur" },
                    { max: 32, message: "最大 32 位字符，内容过长，请删减", trigger: "blur", },
                ],
                client_sid: [
                    { required: true, message: "请选择客户", trigger: "change" },
                ],
                supplier_sid: [
                    { required: true, message: "请选择供应商", trigger: "change" },
                ],
                end_date: [
                    { required: true, message: "请选择对账日期", trigger: "change" },
                ],
            },
            oldCode: '',
            formData: {},
            clientOptions: {
                disabled: false,
                placeholder: '请选择客户',
                bottomAction: {
                    permission: 'save_sys_client',
                    permissionUrl: '/sysClients',
                },
            },
            supplierOptions: {
                disabled: false,
                placeholder: '请选择供应商',
                bottomAction: {
                    permission: 'save_sys_supplier',
                    permissionUrl: '/sysSupplier',
                },
            },
            dataList: [],
            tableOptions: {
                ref: "JxcReconciliationFormTable",
                container: ".jxc_reconciliation_form_container",
                showSummary: true,
                summaryArray: [ 'qty', 'amount', 'payment_amount' ],
                columns: [],
                baseColumns: [
                    {
                        label: "日期",
                        prop: "the_date",
                        align: "center",
                        width: 90,
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "物料",
                        prop: "goods_name",
                        align: "center",
                        width: 120,
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "规格",
                        prop: "spec_info",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                        tooltip: false,
                        cellRender: {
                            name: 'TagList',
                            showTag: true,
                            tagField: 'name',
                            tagTextFun(item) {
                                return `${ item.specification }：${ item.value }`;
                            },
                        },
                    },
                    {
                        label: "单价",
                        prop: "price",
                        align: "right",
                        headerAlign: 'center',
                        footerAlign: 'center',
                        width: 100,
                        permission: [ 'sale', 'buy' ],
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 4),
                    },
                    {
                        label: "数量",
                        prop: "qty",
                        align: "right",
                        headerAlign: 'center',
                        footerAlign: 'center',
                        width: 100,
                        permission: [ 'sale', 'buy' ],
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 3, true),
                    },
                    {
                        label: "单位",
                        prop: "unit",
                        align: "center",
                        width: 60,
                        permission: [ 'sale', 'buy' ],
                    },
                    {
                        label: "金额",
                        prop: "amount",
                        align: "right",
                        headerAlign: 'center',
                        footerAlign: 'center',
                        width: 100,
                        permission: [ 'sale', 'buy' ],
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "收款金额",
                        prop: "payment_amount",
                        align: "right",
                        headerAlign: 'center',
                        footerAlign: 'center',
                        width: 100,
                        permission: [ 'sale' ],
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "付款金额",
                        prop: "payment_amount",
                        align: "right",
                        headerAlign: 'center',
                        footerAlign: 'center',
                        width: 100,
                        permission: [ 'buy' ],
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 2),
                    },
                    {
                        label: "备注",
                        prop: "note_info",
                        align: "center",
                        permission: [ 'sale', 'buy' ],
                        editRender: {
                            name: 'CustomInput',
                        },
                    },
                ],
                operates: {
                    fixed: "right",
                    list: [
                        {
                            id: 'del',
                            icon: 'fa fa-trash-o',
                            size: 'mini',
                            type: 'danger',
                            show: true,
                            tooltip: {
                                content: '删除',
                            },
                            filter: (row) => {
                                return _this.isEditFlag;
                            },
                            method: (index, row) => {
                                let dataList = _this.dataList.map(item => $.extend({}, item));
                                dataList = dataList.filter(item => item._index !== row._index);
                                _this.dataList = _this.resetIndex(dataList);
                                _this.calc();
                            }
                        }
                    ],
                },
                pagination: false,
            },
        };
    },
    computed: {
        ...mapState('jxc', ['setting']),
        isEditFlag() {
            if (this.detail) {
                return false;
            }
            return this.$utils.isEmpty(this.formData.audit_state) || this.formData.audit_state === 0;
        },
        disabledPreEndAmount() {
            if (this.isEditFlag) {
                if (['sale'].indexOf(this.type) !== -1 && !this.$utils.isNotEmpty(this.formData.client_sid)) {
                    return true;
                }
                if (['buy'].indexOf(this.type) !== -1 && !this.$utils.isNotEmpty(this.formData.supplier_sid)) {
                    return true;
                }
                return this.$utils.isNotEmpty(this.formData.init_pre_end_amount) && Number(this.formData.init_pre_end_amount) > 0;
            }
            return true;
        },
    },
    watch: {
        row: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        async init() {
            const _this = this;
            if (!_this.row) {
                return;
            }
            await _this.storeDispatch('jxc/initSetting');
            _this.formData = {};
            _this.initTableOptions();
            if (_this.$refs.jxcReconciliationForm) {
                _this.$refs.jxcReconciliationForm.clearValidate();
            }
            let sid = _this.$route.query.sid;
            if (_this.$utils.isNotEmpty(_this.row.sid)) {
                sid = _this.row.sid;
            }
            if (_this.$utils.isNotEmpty(sid)) {
                await _this.initData(_this.row.sid);
            } else {
                _this.formData = {
                    end_date: _this.$XEUtils.toDateString(new Date(), 'yyyy-MM-dd'),
                };
            }
            if (_this.detail) {
                _this.rules = {};
            }
        },
        initTableOptions() {
            const _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            columns = columns.filter(item => item.permission.indexOf(_this.type) !== -1);
            columns = clothing.resetTableColumns(_this.setting, columns);
            columns = columns.map(item => {
                let obj = $.extend({}, item);
                if (!_this.isEditFlag || item.prop !== 'note_info') {
                    delete obj.editRender;
                }
                return obj;
            });
            let operates = $.extend({}, _this.tableOptions.operates);
            if (!_this.isEditFlag) {
                operates = {};
            }
            _this.tableOptions = $.extend({}, _this.tableOptions, {
                columns, operates,
                getMaxHeight() {
                    let height = $(_this.getActiveTabsContainer()).height();
                    return height * 0.8 - 250;
                },
            });
        },
        initData(sid) {
            const _this = this;
            return _this.fetchData(_this.$api.API_GetJxcFinancePaymentRequestBySid, {
                sid,
            }).then(result => {
                let resData = result.data || {};
                let dataList = clothing.transferDetailList(_this.setting, resData.detail_list, _this.tableOptions.columns);
                _this.formData = $.extend({}, _this.formData, resData);
                _this.dataList = _this.resetIndex(dataList);
                _this.oldCode = resData.code;
            }).catch(() => {
            });
        },
        generateCode() {
            const _this = this;
            if (_this.type === 'sale' && _this.$utils.isEmpty(_this.formData.client_sid)) {
                return;
            }
            if (_this.type === 'buy' && _this.$utils.isEmpty(_this.formData.supplier_sid)) {
                return;
            }
            if (_this.$utils.isNotEmpty(_this.oldCode) && _this.oldCode === _this.formData.code) {
                return;
            }
            return _this.storeDispatch('base/getAutoOrderCode', {
                rule_code: _this.type === 'sale' ? 'jxc_fin_reconciliation_sale' : 'jxc_fin_reconciliation_buy',
                related_party_sid: _this.formData.client_sid,
            }).then(data => {
                _this.formData = $.extend({}, _this.formData, {
                    code: data,
                });
                _this.oldCode = data;
                if (_this.$refs.jxcReconciliationForm) {
                    _this.$refs.jxcReconciliationForm.clearValidate('code');
                }
            });
        },
        handleClientEvent(event) {
            const _this = this;
            if (!_this.isEditFlag) {
                return;
            }
            if (typeof event.value !== 'undefined' && _this.$utils.isNotEmpty(event.value)) {
                _this.formData = $.extend({}, _this.formData, {
                    client_sid: event.value,
                });
                if (_this.isEditFlag) {
                    _this.generateCode();
                    _this.initFormData();
                    if (event.value !== _this.row.client_sid) {
                        _this.clear();
                    }
                }
            }
        },
        handleSupplierEvent(event) {
            const _this = this;
            if (!_this.isEditFlag) {
                return;
            }
            if (typeof event.value !== 'undefined' && _this.$utils.isNotEmpty(event.value)) {
                _this.formData = $.extend({}, _this.formData, {
                    supplier_sid: event.value,
                });
                if (_this.isEditFlag) {
                    _this.generateCode();
                    _this.initFormData();
                    if (event.value !== _this.row.supplier_sid) {
                        _this.clear();
                    }
                }
            }
        },
        initFormData() {
            const _this = this;
            if (_this.$utils.isNotEmpty(_this.formData.sid)) {
                return;
            }
            if (_this.type === 'sale' && _this.$utils.isEmpty(_this.formData.client_sid)) {
                return;
            }
            if (_this.type === 'buy' && _this.$utils.isEmpty(_this.formData.supplier_sid)) {
                return;
            }
            return _this.fetchData(_this.$api.API_GetInitRequestFormData, {
                type: _this.type,
                client_sid: _this.formData.client_sid,
                supplier_sid: _this.formData.supplier_sid,
            }).then(result => {
                let resData = result.data || {};
                if (_this.$utils.isNotEmpty(_this.formData.sid)) {
                    _this.formData = $.extend({}, _this.formData, {
                        init_pre_end_amount: resData.pre_end_amount
                    });
                } else {
                    _this.formData = $.extend({}, _this.formData, resData, {
                        init_pre_end_amount: resData.pre_end_amount
                    });
                }
            }).catch(() => {
            });
        },
        clear () {
            this.dataList = [];
            this.calc();
        },
        openSelectDialog() {
            const _this = this;
            if (_this.type === 'sale' && _this.$utils.isEmpty(_this.formData.client_sid)) {
                _this.$message.error('请选择客户');
                return;
            }
            if (_this.type === 'buy' && _this.$utils.isEmpty(_this.formData.supplier_sid)) {
                _this.$message.error('请选择供应商');
                return;
            }
            _this.$dialog({
                title: '选单',
                width: '1000px',
                component: {
                    value: SelectOrderAndBill,
                    props: {
                        data: {
                            client_sid: _this.formData.client_sid,
                            supplier_sid: _this.formData.supplier_sid,
                            type: _this.type,
                            selectList: _this.dataList,
                            sid: _this.formData.sid,
                            setting: _this.setting,
                        },
                    },
                },
                confirmed(dialog) {
                    _this.dataList = _this.procSelectionList(dialog.selectionList);
                    _this.calc();
                },
            });
        },
        procSelectionList(data) {
            const _this = this;
            let list = [];
            if (_this.$utils.isNotEmptyList(data)) {
                data.forEach(item => {
                    let obj = $.extend({}, item);
                    if (_this.$utils.isNotEmptyList(item.cut_money_list)) {
                        let cutMoneyList = item.cut_money_list.map(t => $.extend({}, t));
                        if (_this.$utils.isEmpty(_this.formData.sid)) {
                            cutMoneyList = cutMoneyList.filter(t => t.pay_req_state !== 1);
                            if (_this.$utils.isEmpty(item.pay_req_state) || item.pay_req_state === 0) {
                                list.push(obj);
                            }
                        } else {
                            if (item.request_sid === _this.formData.sid) {
                                list.push(obj);
                            }
                            cutMoneyList = cutMoneyList.filter(t => t.pay_req_state !== 1 || t.req_sid === _this.formData.sid);
                        }
                        cutMoneyList.forEach(cutObj => {
                            list.push({
                                id: cutObj.req_detail_id,
                                sid: cutObj.req_detail_sid,
                                src_type: 'cut',
                                src_sid: cutObj.sid,
                                src_parent_sid: cutObj.order_detail_sid,
                                the_date: _this.$utils.formatDate(cutObj.create_date, 'yyyy-MM-dd'),
                                goods_name: cutObj.client_code,
                                unit: cutObj.unit,
                                amount: -cutObj.cut_amount,
                            });
                        });
                        delete obj.cut_money_list;
                    } else {
                        list.push(obj);
                    }
                });
            }
            return _this.resetIndex(list);
        },
        calc() {
            const _this = this;
            let amount = 0, paymentAmount = 0, endAmount = (_this.formData.pre_end_amount || 0);
            if (_this.$utils.isNotEmptyList(_this.dataList)) {
                _this.dataList.forEach(item => {
                    if (_this.$utils.isNotEmpty(item.amount)) {
                        amount = _this.$utils.accAdd(amount, item.amount);
                        endAmount = _this.$utils.accAdd(endAmount, item.amount);
                    }
                    if (_this.$utils.isNotEmpty(item.payment_amount)) {
                        paymentAmount = _this.$utils.accAdd(paymentAmount, item.payment_amount);
                        endAmount = _this.$utils.accSubtr(endAmount, item.payment_amount);
                    }
                });
            }
            _this.formData = $.extend({}, _this.formData, {
                amount: Number(amount),
                payment_amount: Number(paymentAmount),
                end_amount: Number(endAmount),
            });
        },
        async confirm () {
            const _this = this;
            let valid = await _this.validateForm('jxcReconciliationForm');
            if (!valid) {
                return false;
            }
            if (!_this.$utils.isNotEmptyList(_this.dataList)) {
                _this.$message.error('对账明细不能为空');
                return false;
            }
            let dataList = clothing.procSubData(_this.setting, _this.dataList);
            let subData = $.extend({}, _this.formData);
            subData.type = _this.type;
            subData.detail_list = dataList.map(item => {
                let obj = $.extend({}, item);
                obj.sn = item._index + 1;
                if (item.src_type !== 'cut') {
                    delete obj.amount;
                }
                return obj;
            });
            return _this.fetchData(_this.$api.API_SaveJxcFinancePaymentRequest, subData).then(() => {
                _this.$message.success('保存成功！');
                return true;
            }).catch(() => {
                return false;
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.jxc_reconciliation_form_container {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
</style>
